import React, { useState, useEffect } from 'react';
import { Link as RouterLink } from 'react-router-dom';
import {
    Box,
    Button,
    Card,
    CardActions,
    CardContent,
    CardMedia,
    Container,
    Grid,
    IconButton,
    Menu,
    MenuItem,
    Typography,
    Divider,
    Chip,
    Dialog,
    DialogActions,
    DialogContent,
    DialogContentText,
    DialogTitle,
} from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import MoreVertIcon from '@mui/icons-material/MoreVert';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';
import ShareIcon from '@mui/icons-material/Share';
import VisibilityIcon from '@mui/icons-material/Visibility';
import DownloadIcon from '@mui/icons-material/Download';
import { useAuth } from '../contexts/AuthContext';

const Dashboard = () => {
    const { currentUser } = useAuth();
    const [resumes, setResumes] = useState([]);
    const [loading, setLoading] = useState(true);
    const [anchorEl, setAnchorEl] = useState(null);
    const [selectedResumeId, setSelectedResumeId] = useState(null);
    const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
    const [shareDialogOpen, setShareDialogOpen] = useState(false);

    // Mock resume data - in a real app, this would come from an API
    useEffect(() => {
        // Simulate API call
        setTimeout(() => {
            setResumes([
                {
                    id: '1',
                    title: '软件工程师简历',
                    template: 'modern',
                    updatedAt: '2023-05-15T10:30:00Z',
                    previewImage: 'https://via.placeholder.com/300x400?text=Resume+Preview',
                    isPublic: true,
                    viewCount: 45
                },
                {
                    id: '2',
                    title: '产品经理简历',
                    template: 'professional',
                    updatedAt: '2023-04-20T14:15:00Z',
                    previewImage: 'https://via.placeholder.com/300x400?text=Resume+Preview',
                    isPublic: false,
                    viewCount: 12
                },
                {
                    id: '3',
                    title: '市场营销简历',
                    template: 'creative',
                    updatedAt: '2023-03-10T09:45:00Z',
                    previewImage: 'https://via.placeholder.com/300x400?text=Resume+Preview',
                    isPublic: true,
                    viewCount: 28
                }
            ]);
            setLoading(false);
        }, 1000);
    }, []);

    const handleMenuOpen = (event, resumeId) => {
        setAnchorEl(event.currentTarget);
        setSelectedResumeId(resumeId);
    };

    const handleMenuClose = () => {
        setAnchorEl(null);
    };

    const handleDeleteClick = () => {
        handleMenuClose();
        setDeleteDialogOpen(true);
    };

    const handleShareClick = () => {
        handleMenuClose();
        setShareDialogOpen(true);
    };

    const handleDeleteConfirm = () => {
        // In a real app, this would call an API to delete the resume
        setResumes(resumes.filter(resume => resume.id !== selectedResumeId));
        setDeleteDialogOpen(false);
    };

    const handleDeleteCancel = () => {
        setDeleteDialogOpen(false);
    };

    const handleShareClose = () => {
        setShareDialogOpen(false);
    };

    const formatDate = (dateString) => {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: 'long',
            day: 'numeric'
        });
    };

    return (
        <Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
            {/* Dashboard Header */}
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 4 }}>
                <Box>
                    <Typography variant="h4" gutterBottom>
                        我的简历
                    </Typography>
                    <Typography variant="body1" color="text.secondary">
                        欢迎回来，{currentUser?.name}！管理您的所有简历。
                    </Typography>
                </Box>
                <Button
                    variant="contained"
                    startIcon={<AddIcon />}
                    component={RouterLink}
                    to="/editor/new"
                >
                    创建新简历
                </Button>
            </Box>

            {/* Resume List */}
            <Grid container spacing={4}>
                {resumes.map((resume) => (
                    <Grid item key={resume.id} xs={12} sm={6} md={4}>
                        <Card sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
                            <CardMedia
                                component="img"
                                height="200"
                                image={resume.previewImage}
                                alt={resume.title}
                            />
                            <CardContent sx={{ flexGrow: 1 }}>
                                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                                    <Typography variant="h6" component="h2" gutterBottom>
                                        {resume.title}
                                    </Typography>
                                    <IconButton
                                        aria-label="resume options"
                                        onClick={(e) => handleMenuOpen(e, resume.id)}
                                    >
                                        <MoreVertIcon />
                                    </IconButton>
                                </Box>
                                <Typography variant="body2" color="text.secondary" gutterBottom>
                                    最后更新: {formatDate(resume.updatedAt)}
                                </Typography>
                                <Box sx={{ mt: 1 }}>
                                    <Chip
                                        size="small"
                                        label={resume.isPublic ? '公开' : '私密'}
                                        color={resume.isPublic ? 'success' : 'default'}
                                        sx={{ mr: 1 }}
                                    />
                                    <Chip
                                        size="small"
                                        label={`${resume.viewCount} 次浏览`}
                                        variant="outlined"
                                    />
                                </Box>
                            </CardContent>
                            <Divider />
                            <CardActions>
                                <Button
                                    size="small"
                                    startIcon={<EditIcon />}
                                    component={RouterLink}
                                    to={`/editor/${resume.id}`}
                                >
                                    编辑
                                </Button>
                                <Button
                                    size="small"
                                    startIcon={<VisibilityIcon />}
                                    component={RouterLink}
                                    to={`/resume/${resume.id}`}
                                >
                                    预览
                                </Button>
                                <Button
                                    size="small"
                                    startIcon={<ShareIcon />}
                                    onClick={handleShareClick}
                                >
                                    分享
                                </Button>
                            </CardActions>
                        </Card>
                    </Grid>
                ))}
            </Grid>

            {/* Resume Options Menu */}
            <Menu
                anchorEl={anchorEl}
                open={Boolean(anchorEl)}
                onClose={handleMenuClose}
            >
                <MenuItem
                    component={RouterLink}
                    to={`/editor/${selectedResumeId}`}
                    onClick={handleMenuClose}
                >
                    <EditIcon fontSize="small" sx={{ mr: 1 }} /> 编辑
                </MenuItem>
                <MenuItem
                    component={RouterLink}
                    to={`/resume/${selectedResumeId}`}
                    onClick={handleMenuClose}
                >
                    <VisibilityIcon fontSize="small" sx={{ mr: 1 }} /> 预览
                </MenuItem>
                <MenuItem onClick={handleShareClick}>
                    <ShareIcon fontSize="small" sx={{ mr: 1 }} /> 分享
                </MenuItem>
                <MenuItem onClick={handleMenuClose}>
                    <DownloadIcon fontSize="small" sx={{ mr: 1 }} /> 导出 PDF
                </MenuItem>
                <Divider />
                <MenuItem onClick={handleDeleteClick} sx={{ color: 'error.main' }}>
                    <DeleteIcon fontSize="small" sx={{ mr: 1 }} /> 删除
                </MenuItem>
            </Menu>

            {/* Delete Confirmation Dialog */}
            <Dialog
                open={deleteDialogOpen}
                onClose={handleDeleteCancel}
            >
                <DialogTitle>确认删除</DialogTitle>
                <DialogContent>
                    <DialogContentText>
                        您确定要删除这份简历吗？此操作无法撤销。
                    </DialogContentText>
                </DialogContent>
                <DialogActions>
                    <Button onClick={handleDeleteCancel}>取消</Button>
                    <Button onClick={handleDeleteConfirm} color="error" autoFocus>
                        删除
                    </Button>
                </DialogActions>
            </Dialog>

            {/* Share Dialog */}
            <Dialog
                open={shareDialogOpen}
                onClose={handleShareClose}
            >
                <DialogTitle>分享简历</DialogTitle>
                <DialogContent>
                    <DialogContentText gutterBottom>
                        通过以下链接分享您的简历：
                    </DialogContentText>
                    <Box sx={{ bgcolor: 'grey.100', p: 2, borderRadius: 1 }}>
                        <Typography variant="body2" component="code">
                            https://resumeshare.com/share/{selectedResumeId}
                        </Typography>
                    </Box>
                </DialogContent>
                <DialogActions>
                    <Button onClick={handleShareClose}>关闭</Button>
                    <Button onClick={handleShareClose} color="primary">
                        复制链接
                    </Button>
                </DialogActions>
            </Dialog>
        </Container>
    );
};

export default Dashboard; 